package com.hctforgreen.greenservice.ui.adapter;

import android.app.Activity;
import android.content.Context;
import android.os.Handler;
import android.os.Message;
import android.text.TextUtils;
import android.view.LayoutInflater;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.ViewGroup;
import android.widget.BaseAdapter;
import android.widget.ImageView;
import android.widget.ListView;
import android.widget.TextView;
import android.widget.Toast;

import com.hctforgreen.greenservice.R;
import com.hctforgreen.greenservice.ctr.DbController;
import com.hctforgreen.greenservice.ctr.HctController;
import com.hctforgreen.greenservice.model.BookListEntity.BookEntity;
import com.hctforgreen.greenservice.model.LoginResultEntity;
import com.hctforgreen.greenservice.model.StudyEntity;
import com.hctforgreen.greenservice.utils.HctConstants;
import com.hctforgreen.greenservice.utils.HctResult;
import com.hctforgreen.greenservice.utils.LoginResultStoreUtil;

import java.util.HashMap;
import java.util.List;
import java.util.Map;

import cn.dns.reader.network.Util;

/**
 * 学习资料适配器
 *
 * @author dhb 20150502
 */
public class StudyListAdapter extends BaseAdapter {

    private Activity context;
    private List<StudyEntity> myList;
    private String downloadUrl;
    private ListView mListView;

    StudyEntity studyEntity;
    Map<Integer, Boolean> map = new HashMap<Integer, Boolean>();

    public StudyListAdapter(Activity context, List<StudyEntity> myList, ListView listView) {
        this.context = context;
        this.myList = myList;
        this.mListView = listView;
    }

    public int getCount() {
        return myList.size();
    }

    public Object getItem(int position) {
        return myList.get(position);
    }

    public long getItemId(int position) {
        return position;
    }

    public View getView(final int position, View convertView, ViewGroup parent) {
        ViewHolder holder = null;
        if (convertView == null) {
            holder = new ViewHolder();
            convertView = LayoutInflater.from(context).inflate(R.layout.item_praise, null);
            holder.tvName = (TextView) convertView.findViewById(R.id.tv_name);
            holder.tvDate = (TextView) convertView.findViewById(R.id.tv_date);
            holder.tvDownloads = (TextView) convertView.findViewById(R.id.tv_downloads);
            holder.tvPraises = (TextView) convertView.findViewById(R.id.tv_praises);
            holder.tvExamStatus = (TextView) convertView.findViewById(R.id.tv_exam_status);
            holder.imgExam = (ImageView) convertView.findViewById(R.id.has_exame);
            holder.imgDownload = (ImageView) convertView.findViewById(R.id.btn_download);
            holder.tvDownlaoded = (TextView) convertView.findViewById(R.id.tv_downloaded);
            holder.tvPraises = (TextView) convertView.findViewById(R.id.tv_praise);
            holder.tvStep = (TextView) convertView.findViewById(R.id.tv_step);
            holder.imgPraise = (ImageView) convertView.findViewById(R.id.img_praise);
            holder.imgStep = (ImageView) convertView.findViewById(R.id.img_step);


            holder.pView = convertView.findViewById(R.id.lyt_study_book);
            convertView.setTag(holder);
        } else {
            holder = (ViewHolder) convertView.getTag();
        }


        studyEntity = myList.get(position);
        holder.tvName.setText(studyEntity.title);
        holder.tvDate.setText(studyEntity.date);
        holder.tvDownloads.setText(context
                .getString(R.string.study_list_downloads) + studyEntity.downloads);
        holder.tvPraises.setText(studyEntity.getPraises());
        holder.tvStep.setText(studyEntity.getStep());
        //设置考试状态
        if (studyEntity.getExamStatus().equals("0")) {
            holder.tvExamStatus.setText("未考试");
            holder.tvExamStatus.setTextColor(context.getResources().getColor(R.color.gray_not_test));
        } else if (studyEntity.getExamStatus().equals("1")) {
            holder.tvExamStatus.setText("未通过");
            holder.tvExamStatus.setTextColor(context.getResources().getColor(R.color.gray_not_pass));
        } else if (studyEntity.getExamStatus().equals("2")) {
            holder.tvExamStatus.setText("考试通过");
            holder.tvExamStatus.setTextColor(context.getResources().getColor(R.color.gray_pass_test));
        }

        /**
         * 2016 11 22
         * 点赞、踩处理
         */
        holder.imgPraise.setOnClickListener(new OnClickListener() {
            @Override
            public void onClick(final View view) {

                if (myList.get(position).getEvaluate().equals("")) {
                    praise_step(position, myList.get(position), view, "1");
                } else {
                    toa.show(context, "您已经进行过评价");
                }
            }
        });
        holder.imgStep.setOnClickListener(new OnClickListener() {
            @Override
            public void onClick(View view) {
                if (myList.get(position).getEvaluate().equals("")) {
                    praise_step(position, myList.get(position), view, "0");
                } else {
                    toa.show(context, "您已经进行过评价");
                }
            }
        });

        /**
         * 2016 11 18 390778
         * 进行保存是否点击过
         */
        if (studyEntity.evaluate.equals("")) {
            map.put(position, false);
            holder.imgPraise.setImageResource(R.drawable.good_no);
            holder.imgStep.setImageResource(R.drawable.bad_no);
        }
        if (studyEntity.evaluate.equals("0")) {
            map.put(position, true);
            holder.imgPraise.setImageResource(R.drawable.good_no);
            holder.imgStep.setImageResource(R.drawable.bad);
        }
        if (studyEntity.evaluate.equals("1")) {
            map.put(position, true);
            holder.imgPraise.setImageResource(R.drawable.good);
            holder.imgStep.setImageResource(R.drawable.bad_no);
        }

        initStudyBook(holder, studyEntity);
        return convertView;
    }

    /**
     * 2016 11 22
     * 390778
     * 对点赞、踩进行处理，并回传服务器
     */
    private void praise_step(int position, final StudyEntity studyEntity, final View view, final String score) {
        if (map.get(position) == false) {
            final Handler handler = new Handler() {
                @Override
                public void handleMessage(Message msg) {
                    switch (msg.what) {
                        case HctConstants.STATUS_SUCCESS:
                            ImageView img = (ImageView) view;
                            studyEntity.setEvaluate(score);
                            toa.show(context, "谢谢您的点评");
                            if (view.getId() == R.id.img_praise) {
                                studyEntity.setPraises(Integer.parseInt(studyEntity.praises) + 1 + "");
                                img.setImageResource(R.drawable.good);
                            }
                            if (view.getId() == R.id.img_step) {
                                studyEntity.setStep(Integer.parseInt(studyEntity.step) + 1 + "");
                                img.setImageResource(R.drawable.bad_no);
                            }
                            notifyDataSetChanged();
                            break;
                        case HctConstants.STATUS_FAILD:
                            toa.show(context,
                                    context.getString(R.string.net_error_hint));
                            break;
                    }
                }
            };
            new Thread() {
                @Override
                public void run() {
                    Message msg = new Message();

                    HctController controller = new HctController(context);
                    LoginResultEntity resultEntity = LoginResultStoreUtil.get(context);

                    try {
                        if (score.equals("1")) {
                            HctResult result = controller.submitPraise(resultEntity.personId,
                                    studyEntity.id, score);
                            if (result.status == HctConstants.STATUS_SUCCESS) {
                                msg.what = result.status;
                                msg.obj = result;
                            } else {
                                msg.what = HctConstants.STATUS_FAILD;
                            }
                        } else if (score.equals("0")) {
                            HctResult result = controller.submitPraise(resultEntity.personId,
                                    studyEntity.id, score);
                            if (result.status == HctConstants.STATUS_SUCCESS) {
                                msg.what = result.status;
                                msg.obj = result;
                            } else {
                                msg.what = HctConstants.STATUS_FAILD;
                            }
                        }
                    } catch (Exception e) {
                        e.printStackTrace();
                    }
                    handler.sendMessage(msg);
                }
            }.start();
        }
    }


    private void initStudyBook(final ViewHolder holder, StudyEntity entity) {
        if (TextUtils.isEmpty(entity.bookId)) {
            holder.imgDownload.setVisibility(View.INVISIBLE);
            holder.tvDownlaoded.setVisibility(View.GONE);
        } else {
            final DbController controller = new DbController(context);
            final BookEntity bookEntity = controller
                    .getBookEntity(entity.bookId);
            if (bookEntity == null || TextUtils.isEmpty(bookEntity.id)) {
                holder.imgDownload.setVisibility(View.INVISIBLE);
                holder.tvDownlaoded.setVisibility(View.GONE);
            } else {
                if (bookEntity.bookZipState
                        .equals(HctConstants.ON_ACTIVITY_KEY_BOOK_ZIP_STATE_DOWNLOAD_DONE)
                        || (HctConstants.ON_ACTIVITY_KEY_BOOK_ZIP_STATE_ANALISIS_DONE
                        .equals(bookEntity.bookZipState) && bookEntity.bCanUpdate
                        .equals(HctConstants.ON_ACTIVITY_KEY_BOOK_B_CAN_UPDATE_FALSE))) {// 已下载
                    holder.imgDownload.setVisibility(View.GONE);
                    holder.tvDownlaoded.setVisibility(View.VISIBLE);
                } else {// 未下载
                    holder.imgDownload.setVisibility(View.VISIBLE);

                    holder.tvDownlaoded.setVisibility(View.GONE);
                    holder.imgDownload
                            .setOnClickListener(new OnClickListener() {
                                @Override
                                public void onClick(View v) {// 点击下载资料
                                    holder.pView.setTag(bookEntity);
                                    bookEntity.doWhatClick = HctConstants.ON_ACTIVITY_KEY_DO_DOWNLOAD_CLICK;
                                    controller
                                            .updateBookOnWhatClick(bookEntity);

                                    /**
                                     * 调用Service下载
                                     */
                                    Util.doDownloadBook(context, bookEntity);

                                }
                            });
                }
            }
        }

    }


    static class ViewHolder {
        View pView;// itemview
        TextView tvName;// 名称
        TextView tvDate;// 时间
        TextView tvDownloads;// 下载
        TextView tvPraises;// 点赞
        TextView tvExamStatus;//考试状态
        ImageView imgExam;// 考试
        ImageView imgDownload;// 下载
        TextView tvDownlaoded;// 已下载

        TextView tvStep; //点踩
        ImageView imgPraise; //赞的图片
        ImageView imgStep;//踩得图片
    }


    public void notifyDataSetChanged(String downloadUrl) {
        this.downloadUrl = downloadUrl;
        super.notifyDataSetChanged();
    }

    public void updateView(String downloadUrl) {

        int firstVisiblePosition = mListView.getFirstVisiblePosition();
        int lastVisiblePosition = mListView.getLastVisiblePosition();

        int visibleCount = (lastVisiblePosition - firstVisiblePosition);
        for (int i = 0; i <= visibleCount; i++) {
            View visibleView = mListView.getChildAt(i);

            if (visibleView == null) {
                continue;
            }
            View bookLyt = (View) visibleView.findViewById(R.id.lyt_study_book);
            if (bookLyt == null) {
                continue;
            }
            BookEntity tagBook = (BookEntity) bookLyt.getTag();
            if (tagBook != null && tagBook.download_url.equals(downloadUrl)) {

                final DbController dbController = new DbController(context);
                BookEntity inDbEntity = dbController
                        .getBookEntityUseBookName(tagBook.bookName);
                if (HctConstants.ON_ACTIVITY_KEY_BOOK_ZIP_STATE_DOWNLOAD_DONE
                        .equals(inDbEntity.bookZipState)
                        || (HctConstants.ON_ACTIVITY_KEY_BOOK_ZIP_STATE_ANALISIS_DONE
                        .equals(inDbEntity.bookZipState) && inDbEntity.bCanUpdate
                        .equals(HctConstants.ON_ACTIVITY_KEY_BOOK_B_CAN_UPDATE_FALSE))) {
                    bookLyt.findViewById(R.id.btn_download).setVisibility(
                            View.GONE);
                    bookLyt.findViewById(R.id.tv_downloaded).setVisibility(
                            View.VISIBLE);
                }
            }

        }

    }

    /**
     * 2016 11 22 390778
     * 修改toast,提高按钮弹出toash信息的速度
     */
    ToastUtils toa = new ToastUtils();

    public class ToastUtils {

        private Toast mToast;

        public void show(Context ctx, String text) {
            if (mToast == null) {
                mToast = Toast.makeText(ctx, text, Toast.LENGTH_SHORT);
            } else {
                mToast.setText(text);
            }
            mToast.show();
        }
    }
}